/**
 * 
 */
package kulstats.server;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kulstats.Course;
import kulstats.CourseManager;
import kulstats.Registry;
import kulstats.UserManager;
import kulstats.UserType;

import org.json.simple.JSONObject;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;



/**
 * @author Steven Roose
 *
 */
public class RegisterServlet extends HttpServlet {
    @Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws IOException {
    	resp.sendRedirect("/track");
    }
    
    @Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
    		throws IOException {
    	//all possible submitted values, some may be empty, use the ones needed according to type
    	String newName       = req.getParameter("name");
    	String newMail       = req.getParameter("mail");
    	String newCourses    = req.getParameter("courses");
    	String newMain       = req.getParameter("hoofdrichting");
    	String newSide       = req.getParameter("nevenrichting");
    	
    	UserService userService = UserServiceFactory.getUserService();
    	com.google.appengine.api.users.User aeUser = userService.getCurrentUser();
    	if(newMail != aeUser.getEmail()) {
    		//foutief e-mailadres -> cheating!
    		// ERROR
    	}

    	System.out.println("newCourses: " + newCourses);
    	CourseManager courseManager = Registry.courseManager();
    	String[] courseIdList = newCourses.split(",");
    	System.out.println("courseIdList: " + courseIdList);
    	ArrayList<Course> courseList = new ArrayList<Course>();
    	for(String cId : courseIdList) {
        	System.out.println("courseManager.getCourseByID(cId): " + courseManager.getCourseByID(cId));
    		courseList.add(courseManager.getCourseByID(cId));
    	}

    	System.out.println("courseList: " + courseList);
    	
    	UserManager userManager = Registry.userManager();
    	userManager.registerUser(newName, aeUser.getUserId(), newMail, courseList, UserType.STUDENT, newMain, newSide);
        //resp.setContentType("text/plain");
        //resp.getWriter().println(newName + ", " + newMail + ", " + newCourses);
    	
    	JSONObject answer = new JSONObject();
    	try {
        	answer.put("status", "success");
        	resp.setContentType("text/plain");
        	resp.getWriter().println(answer);
    	}
        catch(Exception e) {
        	
        }
    }
}
